<template>
  <div class="mod-order__membersellorder">
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
      <el-form-item>
        <el-input v-model="state.dataForm.memberUname" placeholder="会员" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="daterange" type="daterange" placeholder="注册日期" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="daterangeChangeHandle"> </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input v-model="state.dataForm.id" placeholder="订单ID" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <ren-select v-model="state.dataForm.memberPaymentMethod" dict-type="platform_payment_methods" placeholder="收款方式"></ren-select>
      </el-form-item>
      <el-form-item>
        <ren-select v-model="state.dataForm.platformPaymentMode" dict-type="platform_payment_mode" placeholder="代付渠道"></ren-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="state.dataForm.platformPaymentName" placeholder="付款账号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <ren-select v-model="state.dataForm.status" dict-type="member_sell_order_st" placeholder="订单状态"></ren-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="state.dataForm.channelCode" placeholder="渠道" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="state.dataForm.createDate" placeholder="创建时间" clearable></el-input>
      </el-form-item>
      <!--      <el-form-item>
        <el-input v-model="state.dataForm.finishDate" placeholder="完成时间" clearable></el-input>
      </el-form-item>-->
      <el-form-item>
        <el-button @click="state.getDataList()">{{ $t("query") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="batchDfHandle">批量代付</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="state.exportHandle()">{{ $t("export") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="dfSettingHandle">代付设置</el-button>
      </el-form-item>
    </el-form>
    <el-table size="default" v-loading="state.dataListLoading" :data="state.dataList" border @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="id" label="订单ID" min-width="175" header-align="center" align="center"></el-table-column>
      <el-table-column prop="channelCode" label="渠道" min-width="120" header-align="center" align="center"></el-table-column>
      <el-table-column prop="memberUname" min-width="140" label="会员" header-align="center" align="center">
        <template #default="scope">
          <div>
            <el-link type="primary" @click="memberDetailHandle(scope.row)">{{ scope.row.memberUname }}</el-link>
            <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start" v-for="(item, index) in matchTags(scope.row.flagIds)" :key="index">
              <svg class="iconfont" aria-hidden="true" :color="item.paramJsonObj?.color">
                <use :xlink:href="`#${item.paramJsonObj?.icon}`"></use>
              </svg>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="memberPaymentMethod" min-width="100" label="收款方式" header-align="center" align="center">
        <template v-slot="scope">
          <el-tooltip class="box-item">
            <template #content>
              <span>{{ scope.row.paymentMethodDetail || "Loading" }}</span>
            </template>
            <el-link type="primary" @mouseenter="cellPaymentHoverHandle(scope.row)">{{ state.getDictLabel("platform_payment_methods", scope.row.memberPaymentMethod) }}</el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <!--      <el-table-column prop="platformPaymentMode" min-width="100" label="平台渠道" header-align="center" align="center">
        <template v-slot="scope">
          {{ state.getDictLabel("platform_payment_mode", scope.row.platformPaymentMode) }}
        </template>
      </el-table-column>-->
      <el-table-column prop="platformPaymentName" min-width="100" label="付款账号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="amount" label="订单USDT" min-width="100" header-align="center" align="center"></el-table-column>
      <!--
      <el-table-column prop="platformToFbRate" label="平台汇率" min-width="100" header-align="center" align="center"></el-table-column>
-->
      <!--
      <el-table-column prop="binanToFbRate" label="币安汇率" min-width="100" header-align="center" align="center"></el-table-column>
-->
      <el-table-column prop="receiptAmount" label="金额INR" min-width="100" header-align="center" align="center"></el-table-column>

      <!--
      <el-table-column prop="dfFee" label="代付消耗USDT" min-width="110" header-align="center" align="center"></el-table-column>
-->

      <el-table-column label="代付费用" header-align="center" align="center">
        <template v-slot="scope">
          {{ [1, 4, 5].includes(scope.row.status) || scope.row.dfFee === null ? 0 : (scope.row.dfFee - scope.row.amount).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100" header-align="center" align="center">
        <template v-slot="scope">
          <el-tooltip class="box-item">
            <template #content>
              <div style="max-width: 400px">
                <p v-if="scope.row.errMsg2">结果：{{ scope.row.errMsg2 || "" }}</p>
                <p>{{ scope.row.errMsg || "Loading" }}</p>
              </div>
            </template>
            <el-link type="primary" @mouseenter="cellErrorHoverHandle(scope.row)">
              <dict-label dict-type="member_sell_order_st" :dict-value="scope.row.status" :status="{ 1: 'info', 2: 'info', 4: 'warning', 5: 'danger' }"></dict-label>
            </el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <!--
      <el-table-column prop="payCertificateId" label="凭证ID" header-align="center" align="center"></el-table-column>
-->
      <!--
      <el-table-column prop="remark" label="订单备注" header-align="center" align="center"></el-table-column>
-->
      <el-table-column prop="createDate" width="160" label="创建时间" header-align="center" align="center"></el-table-column>
      <!--
      <el-table-column prop="pushPaymentDate" width="155" label="提到渠道时间" header-align="center" align="center"></el-table-column>
-->
      <el-table-column prop="finishDate" width="155" label="耗时" header-align="center" align="center">
        <template v-slot="scope">
          {{ calculateTimeDifferenceHandle(scope.row.pushPaymentDate, scope.row.finishDate) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="180">
        <template v-slot="scope">
          <el-button type="primary" v-if="scope.row.status === 1 || scope.row.status === 2" link @click="updateStatusHandle(scope.row, 1)">成功</el-button>
          <!--
          <el-button type="primary" link @click="updateStatusHandle(scope.row, 2)">取消</el-button>
-->
          <el-button type="primary" v-if="scope.row.status === 1 || scope.row.status === 2" link @click="updateStatusHandle(scope.row, 3)">失败</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit" :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle" @current-change="state.pageCurrentChangeHandle"> </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="state.getDataList"></add-or-update>
    <!-- 会员详情 -->
    <member-detail-drawer ref="memberDetailRef" :key="addKey" @refreshDataList="state.getDataList"></member-detail-drawer>
    <!-- 代付设置弹窗 -->
    <df-setting :key="addKey" ref="dfSettingRef"></df-setting>
    <!-- 修改订单状态 -->
    <update-status :key="addKey" ref="updateStatusRef" @refreshDataList="state.getDataList"></update-status>
  </div>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import baseService from "@/service/baseService";
import { calculateTimeDifference2 } from "@/utils/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, reactive, ref, toRefs, onMounted } from "vue";
import AddOrUpdate from "./membersellorder-add-or-update.vue";
import UpdateStatus from "./membersellorder-update-status.vue";
import MemberDetailDrawer from "@/views/member/member-detail-drawer.vue";
import DfSetting from "@/views/third/df-setting-update.vue";

const view = reactive({
  getDataListURL: "/order/membersellorder/page",
  getDataListIsPage: true,
  exportURL: "/order/membersellorder/export",
  deleteURL: "/order/membersellorder",
  deleteIsBatch: true,
  limit: 20,
  dataForm: {
    memberUname: "",
    id: "",
    memberPaymentMethod: "",
    platformPaymentMode: "",
    platformPaymentName: "",
    createDate: "",
    finishDate: "",
    status: "",
    channelCode: "",
    beginDate: "",
    endDate: ""
  }
});

const daterange: any = ref([]);
const daterangeChangeHandle = (val: any) => {
  if (!val) {
    state.dataForm.beginDate = "";
    state.dataForm.endDate = "";
    return;
  }
  state.dataForm.beginDate = val[0];
  state.dataForm.endDate = val[1];
};

const state = reactive({ ...useView(view), ...toRefs(view) });

const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
  addKey.value++;
  nextTick(() => {
    addOrUpdateRef.value.init(id);
  });
};

const calculateTimeDifferenceHandle = (startTime: any, endTime: any) => {
  if (!startTime || !endTime) return "-";
  return calculateTimeDifference2(startTime, endTime);
};

// 批量代付
const batchDfHandle = () => {
  ElMessageBox.confirm("请确认是否进行代付操作. 继续?", "提示", {
    type: "warning",
    closeOnClickModal: false,
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        let ids: any = state.dataListSelections?.map((item: any) => state.deleteIsBatchKey && item[state.deleteIsBatchKey]);
        instance.confirmButtonLoading = true;
        baseService
          .put(`/order/membersellorder/batch_df`, ids)
          .then(() => {
            done();
            instance.confirmButtonLoading = false;
            ElMessage({
              type: "success",
              message: "操作成功"
            });
          })
          .catch(() => {
            done();
            instance.confirmButtonLoading = false;
          });
      } else {
        done();
      }
    }
  }).then(async () => {
    state.getDataList();
  });
};

// 获取支付卡详情
const getPaymentInfo = async (id: number) => {
  return baseService.get("/member/memberpaymentmethods/" + id);
};

// 获取支付卡详情
const getErrorInfo = async (id: number) => {
  return baseService.get("/order/fundthirdnotifylog/page", { page: 1, limit: 10, platformOrderId: id });
};

// 获取卡信息
const cellPaymentHoverHandle = async (row: any) => {
  if (row.paymentMethodDetail) {
    row.visible = true;
    return;
  }
  let { code, data } = await getPaymentInfo(row.memberPaymentMethodId);
  if (code === 0) {
    row.paymentMethodDetail = data.jsonData;
  }
};

// 获取错误信息
const cellErrorHoverHandle = async (row: any) => {
  if (!row.id) return;
  if (row.errMsg) {
    row.visible2 = true;
    return;
  }
  let { code, data } = await getErrorInfo(row.id);
  if (code === 0 && data.list.length) {
    row.errMsg2 = data.list[0].msg;
    row.errMsg = data.list[0].content;
  }
};

const memberDetailRef = ref();
const memberDetailHandle = (row?: any) => {
  addKey.value++;
  nextTick(() => {
    let info = {
      ...row,
      memberId: row.memberId
    };
    memberDetailRef.value.init(info);
  });
};

const dfSettingRef = ref();
const dfSettingHandle = () => {
  addKey.value++;
  nextTick(() => {
    dfSettingRef.value.init();
  });
};

const updateStatusRef = ref();
const updateStatusHandle = (row: any, type: any) => {
  addKey.value++;
  nextTick(() => {
    updateStatusRef.value.init(JSON.parse(JSON.stringify(row)), type);
  });
};

const flagIds: any = ref([]);
// 获取会员标签
const getTags = () => {
  baseService.get("/member/flag/all").then((res) => {
    flagIds.value = res.data;
  });
};

// 匹配会员标签
const matchTags = (ids: any) => {
  let flagids: any = [];
  if (ids) {
    try {
      let flag = JSON.parse(ids);
      if (flag !== 0) {
        flagids = flag;
      }
    } catch (error) {
      console.log(error);
    }
  }
  let result: any = flagIds.value.filter((item: any) => flagids.includes(item.id));
  return result;
};

onMounted(() => {
  getTags();
});
</script>
